/**
 * FileName: MybatisPlusConfig
 * Author: zlz
 * CreatedDate: 2025/2/27 17:37:48
 * Description:
 * Version: 1.0.0
 */
package com.zlz.parent.basic.springboot.starter.config;

/**
 * @author zlz
 * @date 2025/2/27 17:37:48
 * @description
 */

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zlz.parent.basic.springboot.starter.trace.LoginContext;
import com.zlz.parent.basic.springboot.starter.trace.TraceContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lj on 2020/4/1 14:51
 */
@Configuration
@ConditionalOnClass(MybatisPlusInterceptor.class)
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页锁
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 自定义填充 需要在在你的实体类中使用@TableField注解指定字段填充策略：
     * FieldFill.INSERT表示在插入操作时自动填充该字段，FieldFill.INSERT_UPDATE表示在插入和更新操作时自动填充该字段。
     * 在metaObjectHandler方法中，你需要替换用户ID的获取方式。
     *
     * @return MetaObjectHandler
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                LoginContext userInfo = TraceContext.getUserInfo();
                if (userInfo != null) {
                    this.strictInsertFill(metaObject, "creator", String.class, userInfo.getUserId());
                    this.strictInsertFill(metaObject, "modifier", String.class, userInfo.getUserId());
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                LoginContext userInfo = TraceContext.getUserInfo();
                if (userInfo != null) {
                    this.strictUpdateFill(metaObject, "modifier", String.class, userInfo.getUserId());
                }
            }
        };
    }
}



